-- -----------------------------------------------------------------------------
-- | WonderTek [ 网络无处不在，沟通及时到达 ]
-- -----------------------------------------------------------------------------
-- | Copyright (c) 2012, WonderTek, Inc. All Rights Reserved.
-- -----------------------------------------------------------------------------
-- | Author: xxxx <xxxx@xxxx.com>
-- -----------------------------------------------------------------------------
-- | Desc: 常用功能函数
-- -----------------------------------------------------------------------------
 -- 根据ip地址和端口号组装一个url地址
function getUrl()
    local port = Config:get('server_port')
    if not port or port == '' then
        Config:set('server_port', '7011')
        port = '7011'
    end
    port = ":" .. port
    local server_url = Config:get('server_url')
    if not server_url or server_url == '' then
        Config:set('server_url', '10.225.222.5')
        server_url = '10.225.222.5'
    end
    return 'http://' .. server_url .. port .. '/'
end

-- 获得请求url地址
function getWholeUrl(urlContent, params)
    local url = getUrl()
    local lines = Config:get('lines')
    if not lines and lines ~= '' then
        lines = '10'
    end
    if isPost then
        return url .. urlContent
    end
    if params and params ~= '' then
        return url .. urlContent .. '?' .. 'usercode=' .. Config:get('username') .. '&pagesize=' .. lines.. '&' .. params
    else
        return url .. urlContent .. '?' .. 'usercode=' .. Config:get('username') .. '&pagesize=' .. lines
    end
end

function setAllShoworHide(sprite, isShow)
    Sprite:setVisible(sprite, isShow)
    Sprite:setActive(sprite, isShow)
    Sprite:setEnable(sprite, isShow)
end
function getJsonArrayCount(data)
    local count = 0
    if data then
        if  #data == 0 and type(data[0]) == 'table' then
            count = 1
        else
            count = #data + 1
        end
    else
    return 0
    end
    return count
end
function isStrAllAlphAndNum(str)
    local len = string.len(str)
    for i = 1, len do
        local ch = string.sub(str, i, i)
        if not ((ch >= 'a' and ch <= 'z') or (ch >= 'A' and ch <= 'Z')) then
            if isStrAllNum(ch) == false then
                return false
            end
        end
    end
    return true
end
function isStrAllNum(str)
    local len = string.len(str)
    for i = 1, len do
        local ch = string.sub(str, i, i)
        if ch < '0' or ch > '9' then
            return false
        end
    end
    return true
end

function getCurDateAndTime()
    local year = os.date("*t")["year"]
    local month = os.date("*t")["month"]
    local day = os.date("*t")["day"]
    local hour = os.date("*t")["hour"]
    local minute = os.date("*t")["min"]
    local sec = os.date("*t")["sec"]
    return string.format('%04s-%02s-%02s %02s:%02s:%02s', year, month, day, hour, minute, sec)
end
--取系统日期时间，少一天的误差
function getCurDateAndTimeAddOneDay()
    local now = os.date("*t",os.time())
    local year = now['year']
    local month = now['month']
    local day = now['day']
    local hour = os.date("*t")["hour"]
    local minute = os.date("*t")["min"]
    local sec = os.date("*t")["sec"]
    return string.format('%04s-%02s-%02s %02s:%02s:%02s', year, month, day, hour, minute, sec)
end
function getCurDate()
    local year = os.date("*t")["year"]
    local month = os.date("*t")["month"]
    local day = os.date("*t")["day"]
    return string.format('%04s-%02s-%02s', year, month, day)
end

function SplitWithBlank(szFullString, szSeparator)
    local nFindStartIndex = 1
    local nSplitIndex = 1
    local nSplitArray = {}
    while true do
        local nFindLastIndex = string.find(szFullString, szSeparator, nFindStartIndex)
        if not nFindLastIndex then
            local stringData = string.sub(szFullString, nFindStartIndex, string.len(szFullString))
            nSplitArray[nSplitIndex] = stringData
            break
        end
        local stringData = string.sub(szFullString, nFindStartIndex, nFindLastIndex - 1)
        nSplitArray[nSplitIndex] = stringData
        nFindStartIndex = nFindLastIndex + string.len(szSeparator)
        nSplitIndex = nSplitIndex + 1
    end
    return nSplitArray
end

--判断是否为空
function isEmpty(str)
    if str == nil or str == '' then
        return true
    else
        return false
    end
end

function Split(szFullString, szSeparator)
    local nFindStartIndex = 1
    local nSplitIndex = 1
    local nSplitArray = {}
    while true do
        local nFindLastIndex = string.find(szFullString, szSeparator, nFindStartIndex)
        if not nFindLastIndex then
            local stringData = string.sub(szFullString, nFindStartIndex, string.len(szFullString))
            
            if string.len(stringData) > 0 then
                nSplitArray[nSplitIndex] = stringData
            end
            break
        end
        local stringData = string.sub(szFullString, nFindStartIndex, nFindLastIndex - 1)
        if string.len(stringData) > 0 then
            nSplitArray[nSplitIndex] = stringData
        end
        nFindStartIndex = nFindLastIndex + string.len(szSeparator)
        nSplitIndex = nSplitIndex + 1
    end
    return nSplitArray
end

-- 显示或隐藏搜索提示
function editOnTextChanged(sprite,ncount)
    local hideLabel = Sprite:findChild(sprite, 'hideLabel')
    if ncount > 0 then
        setAllShoworHide(hideLabel, 0)
    else
        setAllShoworHide(hideLabel, 1)
    end
end

--读取本机磁盘的物理地址。如果无SD卡，则使用手机存储，如果存储路径找不到（某些修改过的手机系统），则保存在应用内部
function getLocalDiskPath()
    local path = System:getFlashCardName(1)
    if isEmpty(path) then
        Log:write('SD卡不存在，尝试使用手机存储')
        path = System:getFlashCardName(0)
        if isEmpty(path) then
            Log:write('手机内部存储无法获取，使用应用路径')
            path = 'MODULE:\\com_wondertek_12580\\'
        end
    end
    path = path..'/sqliteDatabase'
    if IO:dirExist(path) == false then
        IO:dirCreate(path)
    end
    Log:write('最终获得的磁盘路径为',path)
    return path
end

-- 后台隐藏应用
function Util:backgroundApp()
    BackgroundApp()
end

-- 格式化手机号码
function formatPhoneNum(phonenum)
    local noCountryCode = string.gsub(phonenum, "+86", "")
    local result = string.gsub(noCountryCode, "[^%d]", "")
    Log:write("格式化的手机号码为:", result)
    return result
end

-- @hewu 检查用户的imei,imsi和手机号是否三码合一
require('framework.sqlite')
function checkDeviceInfo()
    -- 获取用户的imei和imsi号
    Log:write("开始进行三码合一检查...")
    local imeicode = System:getMachineInfo(4) 
    local imsicode = System:getMachineInfo(5) 
    if imeicode == nil or imeicode == '' then
        imeicode = '0'
    end
    if imsicode == nil or imsicode == '' then
        imsicode = '0'
    end
    -- 获取用户手机号
    local mobile = "0"
    local bRet, errMsg, retCountTable
    local databaseName = getLocalDiskPath()..'/jttxlDatabase'
    local sql = "select mobile,tb_c_system.mark4 from tb_c_employee, tb_c_system where tb_c_system.employee_id = tb_c_employee.employee_id"
    bRet, errMsg = Sqlite:open(databaseName) 
    Log:write("打开数据库返回:bRet = "..bRet.." errMsg ="..errMsg)
    bRet, retCountTable, errMsg = Sqlite:query(databaseName, sql)
    Log:write("获取登录用户数据返回:bRet = "..bRet.." errMsg ="..errMsg)
    if tonumber(bRet) ~= 0 then
        Log:write("系统表查询结果: retCountTable =", retCountTable) 
        if retCountTable[1] ~= nil and retCountTable[1][1] ~= nil then 
            mobile = retCountTable[1][1] 
            if retCountTable[1] ~= nil and (retCountTable[1][2] == nil or retCountTable[1][2] == '') then
                local registerCode = updateDeviceInfoToDb(mobile)
                retCountTable[1][2] = registerCode
            end
        end
        if retCountTable[1] ~= nil and retCountTable[1][2] ~= nil and retCountTable[1][2] ~= '' then
            local registerCode = mobile..imeicode..imsicode
            if registerCode ~= retCountTable[1][2] then
                Dialog:show("", "为保证信息安全，请您重新注册", "ok", "reRegister")
                return "-1"
            end
        end
    end
    Log:write("登录用户手机号为: ", mobile)
    -- 进行校验请求
    local url = Alias.url_server..'mobile/device/validate?userCode='..Config:get('employeeId')
    url = url .. '&imsi='..imsicode..'&imei='..imeicode.."&phone="..mobile
    Http:request('checkDevice', url, 1000, {useCache=false})
    return "1"
end

-- @hewu 三码合一校验返回处理
function checkDeviceRespProc()
    local checkDevice = Http:jsonDecode('checkDevice')
    Log:write('checkDevice', checkDevice)
    if checkDevice.msg ~= "SUCCESS" then 
        Dialog:show("", "为保证信息安全，请您重新注册", "ok", "reRegister")
    else
        Config:set('forceUpdateDatabase', "0")
        Log:write("三码合一校验成功！")
    end
end
--------------------------------统计报表相关函数----------------------------
require 'framework.webbrowser'
-- 在webview中显示fusionCharts统计报表
-- @param dataUrl - string 数据源地址UTF-8编码
-- @param charType -- string 
--                    柱状图Column
--                    条形图Bar
--                    折线图line
--                    饼状图pie
--                    仪表盘 AngularGauge
-- @param x,y,w,h - int 坐标位置和长宽度
function showChartInWebView(dataUrl, chartType, x, y, w, h)
    -- 取得云平台服务器地址
    local webcloud = Config:get('webcloud')
    if webcloud == nil or webcloud == '' then 
        Log:write('webcloud server url is missing!')
        return
    end
    Log:write('webcloud:'..webcloud)
    
    -- 解析报表类型
    local swf = ''
    if chartType == 'Column' then
        swf = 'MSColumn3D.swf '
    elseif chartType == 'Bar' then
        swf = 'MSBar3D.swf'
    elseif chartType == 'Pie' then 
        swf = 'Pie3D.swf'
    elseif chartType == 'Line'  then
        swf = 'MSLine.swf'
    elseif chartType == 'AngularGauge'  then
        swf = 'WidgetsCharts/AngularGauge.swf'
    else
        Log:write('unknown chart type:'..chartType)
        return
    end
    
    -- 构造请求地址
    local requestUrl = string.format('http://%s/webcloud/client/chart/chart_show.action?'..
        'dataUrl=%s&swf=%s&renderer=javascript&dataFormat=jsonurl',
        webcloud, dataUrl, swf)
    Log:write('info: showChart() requestUrl', requestUrl)
    
    -- 
    local xscal = SCREEN_WIDTH / 480
    local yscal = SCREEN_HEIGHT / 800
    WebBrowser:create(x, y*yscal, w*xscal, h*yscal)
    WebBrowser:showWebBrowser(1)
    WebBrowser:openUrl(requestUrl)
end

-- 在webview中显示HighCharts统计报表
-- @param title - string 报表标题
-- @param labels - string 报表的底部名称，以逗号分隔
-- @param values - string 与报表底部名称对应的统计值,以逗号分隔，
--                 如果是MULTI类型的报表则以分号分隔,内部再以逗号分隔
-- @param seriesType - string 定义报表类型single/multi/pie
-- @param showType - string 图表的类型 line/spline/bar/column/pie/piedonut
function showHighCharts(title, labels, values, seriesType, showType)
    -- 打印日志
    local param = string.format('showHighCharts(title=%s, label=%s, values=%s, seriesType = %s, showType = %s)', 
        title, labels, values, seriesType, showType)
    Log:write(param)

    -- 取得云平台服务器地址
    local webcloud = Config:get('webcloud')
    if webcloud == nil or webcloud == '' then 
        Log:write('webcloud server url is missing!')
        return
    end
    Log:write('webcloud:'..webcloud)

    -- 检查webview是否打开
    if WebBrowser:isBrowserRun() == 0 then 
        Log:write('showHighCharts：无法显示报表，浏览器未打开！')
        return
    end

    -- 构造请求地址
    local requestUrl = string.format('http://%s/webcloud/client/chart/hc_show.action?'..
        'title=%s&labels=%s&values=%s&seriesType=%s&showType=%s', 
        webcloud, title, labels, values, seriesType, showType)
    Log:write('showHighCharts: requestUrl', requestUrl)
    WebBrowser:openUrl(requestUrl)
end

-- 显示webView
function showWebView(x, y, w, h)
    local xscal = SCREEN_WIDTH / 480
    local yscal = SCREEN_HEIGHT / 800
    WebBrowser:create(x, y*yscal, w*xscal, h*yscal)
    WebBrowser:showWebBrowser(1)
end

-- 关闭报表显示
function closeWebView()
       WebBrowser:showWebBrowser(0)
       WebBrowser:release()
end

-- 显示系统网络设置
function showSysSetting()
    ShowNetSetting()
end

-- 经纬度格式转换
require 'math'
function XY_TO_GPSCOORDINATE(lon, lat)
    -- 转换为数值类型
    lon = tonumber(lon)
    lat = tonumber(lat)
    if lon == nil or lat == nil then 
       Log:write("经纬度参数非法!")
       return
    end
    
    -- 取纬度的整数和小数部分
    ladu = math.floor(lat)
    lafen = (lat - ladu) * 60
    lafenstr = string.gsub(string.format("%013.10f", lafen), "%.", "")
    lafenstr = string.sub(lafenstr, 1, 6)
    ladustr = string.format("%02d", ladu)
    
    -- 取经度的整数和小数部分
    longdu = math.floor(lon)
    longfen = (lon - longdu) * 60
    longfenstr = string.gsub(string.format("%013.10f", longfen), "%.", "")
    longfenstr = string.sub(longfenstr, 1, 6)
    longdustr = string.format("%03d", longdu)
    
    -- 拼接返回字符串
    result = ladustr..lafenstr..longdustr..longfenstr
    Log:write('XY_TO_GPSCOORDINATE result is -->',result)
    return result
end

-- 将table写入指定的文件中
require 'com_wondertek_12580.common.json'
function writeTable2File(tbl, filePath)
    if tbl == nil or type(tbl) ~= "table" then 
        Log:write("writeTable2File:", "待写入的table非法!")
        return
    end
    if filePath == nil then 
        Log:write("writeTable2File:", "文件路径不能为空!")
        return
    end
    local tblStr = encode(tbl)
    -- 获取待写入文件的目录位置
    local _,_,dirPath =  string.find(filePath, '(.+)[/\\].+$')
    if dirPath ~= nil and IO:dirExist(dirPath) == false then 
        IO:dirCreate(dirPath)
    end
    -- 如果文件不存在，需要重新创建
    if IO:fileExist(filePath) == false then 
        IO:fileCreate(filePath) 
    end
    -- 写入TABLE字符串
    IO:fileWrite(filePath, tblStr)
end

-- 对table进行排序
-- @param tbl 待排序的table
-- @param index 下标或列名
-- @param bDesc true 降序, false 升序
function sortTable(tbl, index, bDesc)
    local sortFunc = nil
    local bExists = false
    if (tbl[0] ~= nil) then 
        table.insert(tbl, 1, tbl[0])
        tbl[0] = nil
        bExists =  true
    end
    if bDesc ==  true then 
        sortFunc = function(a, b)  return tonumber(a[index]) > tonumber(b[index]) end
    else
        sortFunc = function(a, b)  return tonumber(a[index]) < tonumber(b[index]) end
    end
    table.sort(tbl, sortFunc)

    if bExists == true then 
        local result = {}
        for i, v in ipairs(tbl) do 
            table.insert(result, i-1, v)
        end
        return result
    else
        return tbl
    end
end

--table转string
function sz_T2S(_t)  
    local szRet = "{"  
    function doT2S(_i, _v)  
        if "number" == type(_i) then  
            szRet = szRet .. "[" .. _i .. "] = "  
            if "number" == type(_v) then  
                szRet = szRet .. _v .. ","  
            elseif "string" == type(_v) then  
                szRet = szRet .. '"' .. _v .. '"' .. ","  
            elseif "table" == type(_v) then  
                szRet = szRet .. sz_T2S(_v) .. ","  
            else  
                szRet = szRet .. "nil,"  
            end  
        elseif "string" == type(_i) then  
            szRet = szRet .. '["' .. _i .. '"] = '  
            if "number" == type(_v) then  
                szRet = szRet .. _v .. ","  
            elseif "string" == type(_v) then  
                szRet = szRet .. '"' .. _v .. '"' .. ","  
            elseif "table" == type(_v) then  
                szRet = szRet .. sz_T2S(_v) .. ","  
            else  
                szRet = szRet .. "nil,"  
            end  
        end  
    end  
    table.foreach(_t, doT2S)  
    szRet = szRet .. "}"  
    return szRet  
end 

-- 附近
function doNearby()
    Log:write("进入附近页面")
    Scene:go(Alias.m_nearby)
end

-- 搜索
function doSearch()
    Log:write("进入搜索页面")
    Scene:go(Alias.m_infoQuery2)
end

-- 采集
function doCollect()
    Log:write("进入采集页面")
    Scene:go(Alias.m_infoAcquisition)
end

-- 更多
function doMore()
    Log:write("进入更多页面")
    Scene:go(Alias.m_more)
end 

-- 退出应用
function doExit()
    Scene:exit()
end

-- 计算str长度
function utfstrlen(str)
    local len = #str;
    local left = len;
    local cnt = 0;
    local arr={0,0xc0,0xe0,0xf0,0xf8,0xfc};
    while left ~= 0 do
    local tmp=string.byte(str,-left);
    local i=#arr;
    while arr[i] do
    if tmp>=arr[i] then left=left-i;break;end
    i=i-1;
    end
    cnt=cnt+1;
    end
    return cnt;
end

-- 安徽省各地市编码
function fillbook()
    local fillbook = 
        {
            {bookId='1',bookHeight='60',bookTitle='名称',bookDetail='采集单位的名称，不包括分店名、英文名、简称等内容'},
            {bookId='2',bookHeight='150',bookTitle='分店名',bookDetail='连锁商户的分店名称，非连锁商户可不填。1、采用路段名称作为分店名称，不使用序号分店名称（第6分店）。2、对于非连锁店填写“单店”'},
            {bookId='3',bookHeight='180',bookTitle='别名/简称',bookDetail='商户的曾用名、英文名、当地俗称、简称等。别名通常是企业的招牌名，以其特有的服务或产品称谓，在消费者中突出其印象。若别名/简称与商户名称相同，则别名/简称不用填写。可以使用逗号间隔，标出多个别名、简称。'},
            {bookId='1',bookHeight='360',bookTitle='联系电话',bookDetail='采集单位的联系电话，允许导入固定电话、手机号及特服号码：'
..'1、固定电话格式为：“区号”＋半角横杠“-”＋电话或“区号”＋半角横杠“-”总机＋半角星号“*”＋“分机”'
..'2、手机号码格式为：直接填写手机号码，校验格式为11位数字；'
..'3、如果商户同时存在固话、手机，固话在前，手机在后；'
..'4、400、800特服号码格式为：400（800）＋半角横杠“-”+三位号码＋半角横杠“-”＋四位号码'
..'5、短号码直接进行填写，不加区号。多个电话，电话之间以半角空格分开；'},
            {bookId='1',bookHeight='180',bookTitle='详细地址',bookDetail='采集单位所在地的详细地址，即投递信函、包裹、电报、邮政汇款等可送达的地址，具体填写格式为：***区/县***路***号************空格＋地址描述'
..'（该字段不能为空，对于热线电话信息，没有地址内容，填写“不详”）'},
            {bookId='1',bookHeight='90',bookTitle='商圈',bookDetail='商圈（机构所在地的城市功能特征），可以使用逗号间隔，标出多个关键词'},
            {bookId='1',bookHeight='90',bookTitle='标志性建筑',bookDetail='企事业单位所处地址若在某大厦等地标，则需要列明（大厦、花园、酒店、步行街）'},
            {bookId='1',bookHeight='120',bookTitle='邮编',bookDetail='邮政部门为实现邮政现代化而制定的代表投递邮件的邮局的一种专用代号，也是这个局投递范围内的居民和单位通信的代号。'},
            {bookId='1',bookHeight='180',bookTitle='营业时间',bookDetail='公布的营业或开放时间，格式为：hh:mm-hh:mm标点符号及半角横杠均为半角（如：“10：00-24：00”）；如有两个营业时间可用半角空格隔开如（10：00-13：00 14：00-19：00 ）；全天营业则注明“24小时”。 营业至凌晨的，上午：hh:mm-凌晨hh:mm'},
            {bookId='1',bookHeight='120',bookTitle='公交路线',bookDetail='到达该单位的乘车路线，通常包括：1、经过该单位的公交线路；2、由火车站、汽车站、机场、码头等交通枢纽到达该单位的换乘线路。'},
            {bookId='1',bookHeight='120',bookTitle='位置描述',bookDetail='以商户周边标志性建筑为参照物，填写与参照物的位置关系，可以用路口、桥梁、大厦等作为参照物；例如：环球贸易中心，位置描述：安贞桥向东150米路南'},
            {bookId='1',bookHeight='60',bookTitle='推荐点',bookDetail='同行业与众不同的特色服务,对外提供的服务内容'},
            {bookId='1',bookHeight='90',bookTitle='商户简介',bookDetail='商户简要而全面的说明。如企业历史、规模、类型、结构、服务、特色等文字性描述。'},
            {bookId='1',bookHeight='60',bookTitle='标签',bookDetail='用于细化商户的特征分类，如体育彩票'},
            {bookId='1',bookHeight='60',bookTitle='面积(m2)',bookDetail='指商家的店铺容纳的面积，统一以平方米的单位。'},
            {bookId='1',bookHeight='90',bookTitle='参考票价',bookDetail='用于旅游景区的票价一般景点都分淡旺季价，如有特殊优惠也请表明价）'},
            {bookId='1',bookHeight='60',bookTitle='信息维护',bookDetail='记录维护信息，如维护时间、维护目的等'},
            
        };
    return fillbook;
end

